import { ReqPage } from "@/api/interface";
import {
	serviceList,
	serviceNodeList,
	serviceRemove,
	serviceStart,
	serviceStop,
	serviceNodeAdd,
	serviceNodeRemove
} from "@/api/modules/service/service";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { useRoute } from "vue-router";
import { dayjs } from "element-plus";
import LoggerDialog from "@/views/system/services/components/loggerDialog";
import MachineSelect from "@/components/Sansan/GatewayDialog/machineSelect";
import { getDictObj } from "@/utils/cacheUtil";
import { ServiceStatusTypes, SvcType } from "@/enums/statusEnum";
import { AuthBtns } from "@/utils/constants";
export default defineComponent({
	setup() {
		// const globalStore = GlobalStore();
		const route = useRoute();
		const operateList = inject<any>(AuthBtns.operateList);
		const nodeState = reactive<any>({ list: [], val: {} });
		const initParam = reactive<ReqPage>({
			pageIndex: 0,
			pageSize: 20,
			appId: route.query.id,
			nodes: ""
		});

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return initParam.nodes ? serviceList(params) : { result: { records: [] } };
		};
		const buttonsList = ref<any>([]);

		const initNode = async () => {
			const { result, code } = await serviceNodeList({
				id: route.query.id
			});
			if (code == 200 && result.records.length) {
				nodeState.list = result.records;
				nodeState.val = nodeState.list[0];
				changeNode();
			} else {
				nodeState.list = [];
				nodeState.val = {};
			}
		};
		const changeNode = () => {
			initParam.nodes = nodeState.val.sn;
			proTable.value.reset();
		};
		const serviceStatusLabels = ref<any>({});
		onMounted(async () => {
			buttonsList.value = [];
			if (operateList.value.some((item: any) => item.path == "start")) {
				buttonsList.value = [...buttonsList.value, { path: "start", title: "启动" }];
			}
			if (operateList.value.some((item: any) => item.path == "stop")) {
				buttonsList.value = [...buttonsList.value, { path: "stop", title: "停止" }];
			}

			initNode();
			serviceStatusLabels.value = await getDictObj("service_status");
		});
		const proTable = ref<any>();
		const submitDel = async (dataList: any[]) => {
			if (!dataList.length) {
				showMsg("请选择要删除的服务", MessageType.warning);
				return;
			}
			confirm({ content: "删除服务后无法找回，确定进行当前操作" }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await serviceRemove({
					id: dataList.map((item: any) => item.id).join(",")
				});
				let ok = showTips(code, `删除服务`, message);
				if (ok) {
					proTable.value.clearSelection();
					proTable.value.reset();
				}
			});
		};
		const start = async (data: any) => {
			if (!data[0]) {
				showMsg("请选择要操作的服务", MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStart({ id: data[0].id });
				showTips(code, "服务启动", message) && proTable.value.getTableList();
			}, 1000);
		};
		const stop = async (data: any) => {
			if (!data[0]) {
				showMsg("请选择要操作的服务", MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStop({ id: data[0].id });
				showTips(code, "服务停止", message) && proTable.value.getTableList();
			}, 1000);
		};
		const clickBtn = async (fn: string, scope: any) => {
			let selectList = scope?.row ? [scope?.row] : scope?.selectList || [];
			switch (fn) {
				case "del":
					submitDel(selectList);
					break;
				case "logger":
					if (selectList && selectList.length != 1) {
						showMsg("请选择一个服务查看日志。", MessageType.warning);
						return;
					}
					let info = { ...(selectList && selectList[0]) };
					loggerDialog.title = "【" + info.name + "】运行日志";
					loggerDialog.detail = info;
					loggerDialog.visible = true;
					break;
				case "stop":
					stop(selectList);
					break;
				case "start":
					start(selectList);
					break;
			}
		};
		onBeforeUnmount(() => {});
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "status", label: "状态", width: "130px" },
			{ prop: "name", label: "名称", width: "180px" },
			{ prop: "bin", label: "执行文件", width: "180px" },
			{ prop: "svcType", label: "安装方式", width: "100px" },
			{ prop: "key", label: "服务标识", width: "180px" },
			{ prop: "arg", label: "启动参数", width: "180px" },
			{ prop: "path", label: "路径", width: "180px" },
			{ prop: "version", label: "版本", width: "180px" },
			{ prop: "createTime", label: "创建时间", width: "180px" },
			{ prop: "updateTime", label: "更新时间", width: "180px" },
			{ prop: "startTime", label: "启动时间", width: "180px" },
			{ prop: "operate", label: "操作", fixed: "right", width: "200px" }
		];
		const loggerDialog = reactive<any>({
			detail: {},
			title: "服务日志",
			visible: false
		});
		const addNode = () => {
			drawerVisible.value = true;
		};
		const options = ref(SvcType);
		const drawerVisible = ref(false);
		const submitAddNode = async (val: any) => {
			if (!val.length) return;
			const res = await serviceNodeAdd({ nodeSn: val[0].sn, appKey: route.query.key });
			let ok = showTips(res.code, "添加服务", res.message);
			if (ok) {
				initNode();
			}
		};
		const delNode = async () => {
			confirm({ content: "删除节点后无法找回，确定进行当前操作" }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await serviceNodeRemove({
					nodeSn: nodeState.val.sn,
					appKey: route.query.key
				});
				let ok = showTips(code, `删除节点`, message);
				if (ok) {
					initNode();
				}
			});
		};
		return () => {
			return (
				<div class="pt-6">
					<MachineSelect v-model:visible={drawerVisible.value} onSubmit={submitAddNode}></MachineSelect>
					<div class="p-6 shadow ml-6 mr-6" style="border: 1px solid #eee;">
						<div class="flex content-center items-center">
							<div class="title-left-line "></div>
							<span class="mr-3 font-bold">节点信息</span>
							<div class="flex flex-1 content-center">
								<el-select
									class="mr-3"
									style="width:200px"
									v-model={nodeState.val}
									placeholder="请选择节点"
									onChange={() => changeNode()}
									value-key="sn"
								>
									{nodeState.list.map((item: any) => {
										return <el-option label={item.sn} value={item} />;
									})}
								</el-select>
								{operateList.value.some((item: any) => item.path == "node-add") && (
									<el-link class="mr-3" type="primary" onClick={addNode}>
										新增节点
									</el-link>
								)}
								{operateList.value.some((item: any) => item.path == "node-del") && (
									<el-link type="danger" onClick={delNode}>
										删除节点
									</el-link>
								)}
							</div>
						</div>
						<div class="p-4 grid grid-cols-2 space-y-2">
							<div class="flex mt-2">
								<div class="w-32">节点SN</div>
								<div class="flex-1">{nodeState.val.sn || "--"}</div>
							</div>
							<div class="flex">
								<div class="w-32">在线状态</div>
								<div class="flex-1">
									<OnlineStatus v-model={nodeState.val.onlineStatus}></OnlineStatus>
								</div>
							</div>
							<div class="flex">
								<div class="w-32">节点名称</div>
								<div class="flex-1">{nodeState.val.name || "--"}</div>
							</div>
							<div class="flex">
								<div class="w-32">末次交互</div>
								<div class="flex-1">
									{(nodeState.val.lastLiveTime && dayjs(nodeState.val.lastLiveTime).format("YYYY-MM-DD hh:mm:ss")) || "--"}
								</div>
							</div>
						</div>
					</div>
					<LoggerDialog
						width="1024px"
						title={loggerDialog.title}
						v-model:visible={loggerDialog.visible}
						detail={loggerDialog.detail}
						footerLabel={["关闭"]}
					/>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : "节点管理"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.type}>
											{item.title}
										</el-button>
									);
								});
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										labels={serviceStatusLabels.value}
										onlineLabel="未知"
										offlineLabel="未安装"
										types={ServiceStatusTypes}
										v-model={scope.row.status}
									></OnlineStatus>
								);
							},
							svcType: (scope: any) => {
								return scope.row.svcType && options.value.filter((item: any) => item.value == scope.row.svcType)[0].label;
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							updateTime: (scope: any) => {
								return dataFormat("datetime", scope.row.updateTime);
							},
							startTime: (scope: any) => {
								return dataFormat("datetime", scope.row.startTime);
							},
							operate: (scope: any) => {
								return (
									<>
										{operateList.value.some((item: any) => item.path == "service-del") && (
											<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("del", scope)}>
												删除
											</el-link>
										)}
										<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("logger", scope)}>
											日志
										</el-link>
									</>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
